package com.chengyu.core.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengyu.core.constants.NewConstant;
import com.chengyu.core.constants.ScencConstant;
import com.chengyu.core.dto.http.MemberAccReduceCarbonInOrOutResponseDTO;
import com.chengyu.core.dto.http.MemberBehaviorRecordRequestDTO;
import com.chengyu.core.dto.tencent.SceneSaveReidDataReqDTO;
import com.chengyu.core.entity.SceneRideCodeData;
import com.chengyu.core.entity.TblMemberEntity;
import com.chengyu.core.entity.TblRideCodeLog;
import com.chengyu.core.enums.ScencEnum;
import com.chengyu.core.mapper.SceneRideCodeDataMapper;
import com.chengyu.core.mapper.TblRideCodeLogMapper;
import com.chengyu.core.request.*;
import com.chengyu.core.response.MerchantShareRuleResp;
import com.chengyu.core.response.TblPointsSceneResp;
import com.chengyu.core.saasopenai.OpenApiHttpReq;
import com.chengyu.core.saasopenai.SaasOpenApiConfig;
import com.chengyu.core.saasopenai.SaasOpenApiHttpTool;
import com.chengyu.core.saasopenai.saaSRestTemplateConfig;
import com.chengyu.core.service.*;
import com.chengyu.core.util.NewRedisUtils;
import com.chengyu.core.util.ali.NewHttpClientUtil;
import com.chengyu.core.util.dingding.DingTalkPushUtil;
import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 乘车码推送数据表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-05-26
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SceneRideCodeDataServiceImpl extends ServiceImpl<SceneRideCodeDataMapper, SceneRideCodeData> implements ISceneRideCodeDataService {

    private final IMerchantShareRuleService iMerchantShareRuleService;
    private final DingTalkPushUtil dingTalkPushUtil;
    private final NewHttpClientUtil newHttpClientUtil;
    private final SaasOpenApiConfig saasOpenApiConfig;
    private final saaSRestTemplateConfig restTemplateConfig;
    private final TblRideCodeLogMapper tblRideCodeLogMapper;
    private final ITblPointsSceneService iTblPointsSceneService;
    private final ITblPointsImpowerService tblPointsImpowerService;
    private final HttpRequestService httpRequestService;
    private final TblMemberService tblMemberService;


    @Value("${apiUrl.rideCod.carInfo}")
    private String carInfo;

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    public String youjia_jpush_offset = "kafka:emission_push_offset:ride_code_cycling";

    @Autowired
    private NewRedisUtils redisUtils;
    /**
     * 武汉市编码
     */
    private String tripCityId = "420100";

    /**
     * 黄石市编码
     */
//    private String tripCityId = "420200";
    @Override
    public BigDecimal getTodayCarbonNumToalByPhoneDate(String phone) {
        return baseMapper.getTodayCarbonNumToalByPhoneDate(phone);
    }

    @Override
    public Integer getTodayCountByPhoneDate(String phone) {
        return baseMapper.getTodayCountByPhoneDate(phone);
    }

    @Override
    public void obtainRideCodeData() throws Exception {

        //这里没有数据  要换标查询
//        List<TblMemberReq> uuidList = tblMemberService.getAllUUid();
        List<PointsImpowerReq> mPhoneList = tblPointsImpowerService.getAllMember();
//        if (CollectionUtils.isEmpty(mPhoneList)) {
//            log.info("-------------obtainRideCodeData----定时获取获取乘车码前一天数据--------uuid为空 --- 退出----->");
//            return;
//        }
        List<String> phoneList = baseMapper.getTodayDate();
        for (String s : phoneList) {
            for (int i = mPhoneList.size() - 1; i >= 0; i--) {
//                String phone = NewEncryptUtils.decrypt(uuidList.get(i).getPhone(), securityConfig.getPhoneAesKey());
                String phone = mPhoneList.get(i).getPhone();
                if (s.equals(phone)) {
                    mPhoneList.remove(i);
                }
            }
        }

        List<MerchantShareRuleResp> merchantList = new ArrayList<>();
        MerchantShareRuleResp metro = iMerchantShareRuleService.getShareRuleByCode(ScencConstant.RIDE_CODE_METRO);
        if (metro != null) {
            merchantList.add(metro);
        }
        MerchantShareRuleResp bus = iMerchantShareRuleService.getShareRuleByCode(ScencConstant.RIDE_CODE_BUS);
        if (bus != null) {
            merchantList.add(bus);
        }

        int pageSize = 5;
        while (!mPhoneList.isEmpty()) {
            List<PointsImpowerReq> splitList = mPhoneList.subList(0, pageSize < mPhoneList.size() ? pageSize : mPhoneList.size());
//            Map<String, String> listToMap = listToMap(mPhoneList);

            Map<String, String> listToMap = mPhoneList.stream().collect(Collectors.toMap(each -> each.getUnionId(), each -> each.getPhone(), (key1, key2) -> key1));
            log.info("listToMap------------》" + listToMap.toString());

            JSONObject jsonObject = new JSONObject();
            long timestamp = System.currentTimeMillis();
            jsonObject.put("unionIdList", mPhoneList.stream().filter(vo -> !StringUtils.isBlank(vo.getUnionId())).map(vo -> vo.getUnionId()).collect(Collectors.toList()));
            jsonObject.put("requestSerialNo", String.valueOf(timestamp));
            jsonObject.put("requestTime", String.valueOf(timestamp / 1000));

            try {
                String result = newHttpClientUtil.doPostJson(carInfo, jsonObject.toJSONString(), null, null);
                JSONObject object = JSONObject.parseObject(result);
                if ("0".equals(object.getString("code"))) {
                    JSONArray array = object.getJSONArray("data");
                    for (Object o : array) {
                        JSONObject data = JSONObject.parseObject(o.toString());

                        String unionId = data.getString("unionId");
                        JSONArray carInfoList = data.getJSONArray("carInfoList");
                        if (CollectionUtils.isEmpty(carInfoList)) {
                            log.info("定时获取获取乘车码前一天数据返回数据---数据为空-----------》");
                            continue;
                        }
                        List<RideCodeDataReqVo> rideCodeDataReqVoList = JSONArray.parseArray(data.getString("carInfoList"), RideCodeDataReqVo.class);
                        // 消息通知
                        JSONObject json = new JSONObject();
                        String phone = listToMap.get(unionId);
                        if (StringUtils.isBlank(phone)) {
                            log.info("定时获取获取乘车码前一天数据返回数据phone数据为空----------unionId:{}》", unionId);
                            continue;
                        }
                        json.put("data", JSONObject.toJSONString(rideCodeDataReqVoList));
                        if (!CollectionUtils.isEmpty(merchantList)) {
                            json.put("merchantList", JSONObject.toJSONString(merchantList));
                        }
//                        json.put("phone", NewEncryptUtils.decrypt(phone, securityConfig.getPhoneAesKey()));

                        json.put("phone", phone);

                        //这里要接受数据
//                        kafkaTemplate.send(NewConstant.RIDECODE_EMISSION_REDUCTION_ENERGY_TOPIC, JSON.toJSONString(json));
                        rideCode(JSON.toJSONString(json));

                        log.info("kafka send 减排量数据推送-乘车码- , topicName：{},log：{}", NewConstant.RIDECODE_EMISSION_REDUCTION_ENERGY_TOPIC, json.toJSONString());
                    }
                }
            } catch (Exception e) {
                log.error("碳碳星球接口异常：{},{}", jsonObject.toJSONString(), e);
                dingTalkPushUtil.pushMsg("碳碳星球接口数据获取失败");
            }
            // 清除已使用过的数据
            splitList.clear();
        }
    }


    @Override
//    @TenantFilter(filter = false)
    public boolean updataExpire(String phone, String typeCode) {
        List<String> list = baseMapper.getEffectiveDate(phone, typeCode);
        if (CollectionUtils.isEmpty(list)) {
            return true;
        }
        if (list.size() != 3) {
            return true;
        }
        String dateTime = list.get(2);
        return baseMapper.updataExpire(phone, dateTime, typeCode);
    }

    @Override
    public Integer getExistingData(String typeCode) {
        return baseMapper.getExistingData(typeCode);
    }

    public Map<String, String> listToMap(List<TblMemberReq> list) {
        Map<String, String> map = new HashMap<>();
        for (TblMemberReq memberReq : list) {
            map.put(memberReq.getUuid(), memberReq.getPhone());
        }
        return map;
    }


    public void rideCode(String recordValue) {
        boolean ackFlag = true;
        try {


            log.info("碳碳星球-开始推送");
            BigDecimal hundred = new BigDecimal(100);
            JSONObject json = JSONObject.parseObject(recordValue);
            String dataStr = json.getString("data");
            String phone = json.getString("phone");


            String merchantListStr = json.getString("merchantList");
            List<MerchantShareRuleResp> merchantList = new ArrayList<>();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(merchantListStr)) {
                merchantList = JSONArray.parseArray(merchantListStr, MerchantShareRuleResp.class);
            }
            log.info("碳碳星球------------》");
            Date date = new Date();
            List<RideCodeDataReqVo> data = JSONArray.parseArray(dataStr, RideCodeDataReqVo.class);



            if (CollectionUtils.isEmpty(data)) {
                log.info("碳碳星球-数据为空-----------》");
                return;
            }
            // 获取场景
            List<TblPointsSceneResp> sceneRespList = iTblPointsSceneService.sceneList();
//            List<TblPointsSceneResp> sceneRespList = pointsFeignClient.sceneList().getData();
//            TblPointsSceneResp metroSceneResp = sceneRespList.stream().filter(item -> ScencConstant.RIDE_CODE_METRO.equals(item.getScenePort())).findFirst().orElse(null);
//            TblPointsSceneResp busSceneResp = sceneRespList.stream().filter(item -> ScencConstant.RIDE_CODE_BUS.equals(item.getScenePort())).findFirst().orElse(null);
            TblPointsSceneResp busSceneResp = sceneRespList.stream().filter(item -> item.getScenePort().contains(ScencConstant.RIDE_CODE_BUS)).findFirst().orElse(null);
            TblPointsSceneResp metroSceneResp = sceneRespList.stream().filter(item -> item.getScenePort().contains(ScencConstant.RIDE_CODE_METRO)).findFirst().orElse(null);

            // 获取减排场景-商户分成规则
//            MerchantShareRuleResp merchantMetro = metroSceneResp == null ? null: merchantFegin.getShareRule(metroSceneResp.getId()).getData();
//            MerchantShareRuleResp merchantBus = busSceneResp == null ? null : merchantFegin.getShareRule(busSceneResp.getId()).getData();
//            MerchantShareRuleResp merchantMetro = metroSceneResp == null ? null: merchantFegin.getShareRuleByCode(ScencConstant.RIDE_CODE_METRO).getData();
//            MerchantShareRuleResp merchantBus = busSceneResp == null ? null : merchantFegin.getShareRuleByCode(ScencConstant.RIDE_CODE_BUS).getData();

            MerchantShareRuleResp merchantMetro = merchantList.stream().filter(item -> ScencConstant.RIDE_CODE_METRO.equals(item.getSceneCode())).findFirst().orElse(null);
            MerchantShareRuleResp merchantBus = merchantList.stream().filter(item -> ScencConstant.RIDE_CODE_BUS.equals(item.getSceneCode())).findFirst().orElse(null);


            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

            int minute = 1;
            SceneRideCodeData rideCodeData = null;
            List<SceneRideCodeData> saveList = new ArrayList<>(data.size());
            Set<String> set = new HashSet<>();

            PointsDetailReq pointsDetailBus = new PointsDetailReq();
            if (merchantBus != null) {
                pointsDetailBus.setMerchantId(merchantBus.getMerchantId());
            }
            List<DetailReq> saveListBus = new ArrayList<>();
//
            PointsDetailReq pointsDetailMetro = new PointsDetailReq();
            if (merchantMetro != null) {
                pointsDetailMetro.setMerchantId(merchantMetro.getMerchantId());
            }

            List<DetailReq> saveListMetro = new ArrayList<>();
            DetailReq detailReq = null;

            for (RideCodeDataReqVo carInfo : data) {
                rideCodeData = new SceneRideCodeData();

//                城市匹配
//                if (!tripCityId.equals(carInfo.getTripCityId())){
//                    continue;
//                }


                //发放减碳量总数
                BigDecimal carbonNumTotal = null;
                //用户可领取减碳量
                BigDecimal carbonNumAdd = null;
                //商户分到减碳量
                BigDecimal merchantCarbon = BigDecimal.ZERO;

                detailReq = new DetailReq();
                detailReq.setType(1);


                detailReq.setPhone(phone);
//                detailReq.setPhone(EncryptUtils.encrypt(phone, securityConfig.getPhoneAesKey()));
                Date payTime = format.parse(carInfo.getTripTime());
                payTime = new Date(payTime.getTime() + (60000 * minute));
                minute++;
                rideCodeData.setPayTime(payTime);
                if ("1".equals(carInfo.getTripType())) {
                    if (busSceneResp == null) {
                        continue;
                    }
                    // 公交
                    set.add("1");
                    carbonNumTotal = new BigDecimal("150");

                    if (merchantBus != null) {
                        // 商户定义了分成规则
                        Integer shareRatio = merchantBus.getShareRatio();
                        //舍去制，截断操作，后面所有数字直接去除。结果会向原点方向对齐
                        merchantCarbon = carbonNumTotal.multiply(new BigDecimal(shareRatio).divide(hundred)).setScale(2, BigDecimal.ROUND_DOWN);
                    }
                    rideCodeData.setMerchantNumAdd(merchantCarbon);
                    if (merchantBus != null && merchantBus.getNoNeedReceive() == 1) {
                        rideCodeData.setMerchantNumAdd(BigDecimal.ZERO);

                        // 商户定义了分成规则，并且设置不用用户领取也分成
                        detailReq.setSceneId(busSceneResp.getId());
//                        detailReq.setSceneCode(busSceneResp.getScenePort());
//                        detailReq.setSceneName(busSceneResp.getSceneName());
                        detailReq.setSceneCode(ScencEnum.RIDE_CODE_BUS.getValue());
                        detailReq.setSceneName(ScencEnum.RIDE_CODE_BUS.getName());
                        detailReq.setCarbonNum(merchantCarbon);
                        detailReq.setRate(merchantBus.getShareRatio());
                        detailReq.setOriginType(1);
                        detailReq.setBusinessData(format.format(rideCodeData.getPayTime()));
                        saveListBus.add(detailReq);
                    }
//                    rideCodeData.setSceneName(busSceneResp.getSceneName());
//                    rideCodeData.setSceneCode(busSceneResp.getScenePort());
                    rideCodeData.setSceneCode(ScencEnum.RIDE_CODE_BUS.getValue());
                    rideCodeData.setSceneName(ScencEnum.RIDE_CODE_BUS.getName());
                } else if ("2".equals(carInfo.getTripType())) {
//                    if (metroSceneResp == null){
//                        continue;
//                    }
//                    //地铁
//                    set.add("2");
//                    carbonNumTotal = new BigDecimal("170");
//
//                    if (merchantMetro != null) {
//                        // 商户定义了分成规则
//                        Integer shareRatio = merchantMetro.getShareRatio();
//                        //舍去制，截断操作，后面所有数字直接去除。结果会向原点方向对齐
//                        merchantCarbon = carbonNumTotal.multiply(new BigDecimal(shareRatio).divide(hundred)).setScale(2, BigDecimal.ROUND_DOWN);
//                    }
//                    rideCodeData.setMerchantNumAdd(merchantCarbon);
//                    if (merchantMetro != null && merchantMetro.getNoNeedReceive() == 1) {
//                        rideCodeData.setMerchantNumAdd(BigDecimal.ZERO);
//
//                        // 商户定义了分成规则，并且设置不用用户领取也分成
//                        detailReq.setSceneId(metroSceneResp.getId());
////                        detailReq.setSceneCode(metroSceneResp.getScenePort());
////                        detailReq.setSceneName(metroSceneResp.getSceneName());
//                        detailReq.setSceneCode(ScencEnum.RIDE_CODE_METRO.getValue());
//                        detailReq.setSceneName(ScencEnum.RIDE_CODE_METRO.getName());
//                        detailReq.setCarbonNum(merchantCarbon);
//                        detailReq.setRate(merchantMetro.getShareRatio());
//                        detailReq.setOriginType(1);
//                        detailReq.setBusinessData(format.format(rideCodeData.getPayTime()));
//                        saveListMetro.add(detailReq);
//                    }
////                    rideCodeData.setSceneName(metroSceneResp.getSceneName());
////                    rideCodeData.setSceneCode(metroSceneResp.getScenePort());
//                    rideCodeData.setSceneCode(ScencEnum.RIDE_CODE_METRO.getValue());
//                    rideCodeData.setSceneName(ScencEnum.RIDE_CODE_METRO.getName());

                } else {
                    log.error("----碳碳星球----乘车码--⽤户⾏程类型有误：{}", carInfo.getTripType());
                    continue;
                }
                carbonNumAdd = carbonNumTotal.subtract(merchantCarbon);


                BigDecimal tnum = (BigDecimal) redisUtils.get("carbonNumTotal_" + phone);

                Integer totalcount = 0;
                Integer count = baseMapper.getTodayCountByPhoneDate(phone);
                totalcount = totalcount + count;
                if (totalcount >= 2) {
                    carbonNumTotal = BigDecimal.valueOf(0);
                    carbonNumAdd = BigDecimal.valueOf(0);
                } else {
                    totalcount++;
                    carbonNumAdd = carbonNumTotal = BigDecimal.valueOf(150);
                }


//
//                BigDecimal  getTodayCarbonNumToalByPhoneDate  =   baseMapper.getTodayCarbonNumToalByPhoneDate(phone);
//                if(getTodayCarbonNumToalByPhoneDate ==null) getTodayCarbonNumToalByPhoneDate =  BigDecimal.valueOf(0);
//
//                getTodayCarbonNumToalByPhoneDate = getTodayCarbonNumToalByPhoneDate.add(tnum);
//
//
//                log.error("getTodayCarbonNumToalByPhoneDate：{}", getTodayCarbonNumToalByPhoneDate);
//                int comparisonResult = getTodayCarbonNumToalByPhoneDate.compareTo(BigDecimal.valueOf(300));
//              if (comparisonResult < 0) {
//                    carbonNumAdd = carbonNumTotal   =  BigDecimal.valueOf(300).subtract(getTodayCarbonNumToalByPhoneDate);;
//                }
//                if (comparisonResult >= 0) {
//                    carbonNumTotal = BigDecimal.valueOf(0);
//                    carbonNumAdd =  BigDecimal.valueOf(0);
//                } else if (comparisonResult < 0) {
//                    carbonNumAdd = carbonNumTotal   =  BigDecimal.valueOf(300).subtract(getTodayCarbonNumToalByPhoneDate);;
//                }


                redisUtils.set("carbonNumTotal" + phone, tnum, 60);


                rideCodeData.setCreateDate(date);
                rideCodeData.setTypeCode(carInfo.getTripType());
                rideCodeData.setPhone(phone);
                rideCodeData.setCarbonNumTotal(carbonNumTotal);
                rideCodeData.setCarbonNumAdd(carbonNumAdd);
                saveList.add(rideCodeData);
            }
            pointsDetailBus.setList(saveListBus);
            pointsDetailMetro.setList(saveListMetro);
            if (CollectionUtils.isEmpty(saveList)) {
                log.info("碳碳星球-推送提前逻辑结束-----保存数据不符合武汉市----数据为空--------------");
//                redisUtils.set(key, offset);
                return;
            }

            MemberMessageReq messageReq = new MemberMessageReq();
            messageReq.setPhone(phone);
            messageReq.setType(2);
            messageReq.setTitle(NewConstant.MEMBER_MESSAGE_TITLE);
            if (!saveBatch(saveList)) {
                log.error("-----------碳碳星球----乘车码-------保存数据异常{}", JSONObject.toJSONString(saveList));
                throw new RuntimeException("-碳碳星球----乘车码--数据异常");
            } else {
                log.info("碳碳星球-推送减排量到tencent-----------》");
                // 推送减排量到tencent
                SceneSaveReidDataReqDTO reqDTO = null;
                for (SceneRideCodeData sceneRideCodeData : saveList) {
                    String phoneInRecord = sceneRideCodeData.getPhone();
                    QueryWrapper<TblMemberEntity> memberEntityQueryWrapper = new QueryWrapper<>();
                    memberEntityQueryWrapper.eq("phone", phoneInRecord);
                    TblMemberEntity memberEntity = tblMemberService.getOne(memberEntityQueryWrapper);
                    reqDTO = new SceneSaveReidDataReqDTO();
                    reqDTO.setCarbonNum(sceneRideCodeData.getCarbonNumAdd().intValue());
                    reqDTO.setMemberId(memberEntity.getUuid());
                    reqDTO.setExpireDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    log.error(" reqDTO.toString()------{}", reqDTO.toString());
                    httpRequestService.postReduceCarbonToTencent(reqDTO);
                }

                if (set.contains("1")) {
                    updataExpire(phone, "1");
                    messageReq.setImg(busSceneResp.getImg());
                    messageReq.setMessage(ScencEnum.RIDE_CODE_BUS.getName() + ",产生新的减排量,请前往领取");
//                    messageReq.setMessage(busSceneResp.getSceneName()+",产生新的减排量,请前往领取");
//                    if (!memberFeign.saveMessage(messageReq).getData()) {
//                        log.error("----------碳碳星球----乘车码-----保存数据----消息记录-------异常{}", JSONObject.toJSONString(messageReq));
//                    }
                }
                if (set.contains("2")) {
                    updataExpire(phone, "2");
                    messageReq.setImg(metroSceneResp.getImg());
                    messageReq.setMessage(ScencEnum.RIDE_CODE_METRO.getName() + ",产生新的减排量,请前往领取");
//                    if (!memberFeign.saveMessage(messageReq).getData()) {
//                        log.error("----------碳碳星球----乘车码-----保存数据----消息记录-------异常{}", JSONObject.toJSONString(messageReq));
//                    }
                }
            }

            if (!CollectionUtils.isEmpty(saveListBus)) {
//                if (!merchantFegin.updateMerchantCarbon(pointsDetailBus).getData()) {
//                    log.error("------------碳碳星球----乘车码--公交----修改商户账号减排量异常------》");
//                    throw new RuntimeException("--碳碳星球----乘车码--公交-----保存数据异常");
//                }
            }
            if (!CollectionUtils.isEmpty(saveListMetro)) {
//                if (!merchantFegin.updateMerchantCarbon(pointsDetailMetro).getData()) {
//                    log.error("------------碳碳星球----乘车码--地铁----修改商户账号减排量异常------》");
//                    throw new RuntimeException("--碳碳星球----乘车码---地铁------保存数据异常");
//                }
            }

//            if (KaipingEmpowerStats) {
//                //开平推送减排数据
//                JSONObject kaipingJson = new JSONObject();
//                kaipingJson.put("data", JSONObject.toJSONString(saveList));
//                kaipingJson.put("code", ScencEnum.RIDE_CODE_METRO.getValue());
//                kafkaTemplate.send(Constant.KAFKA_KAI_PING_DATA_TOPIC, JSON.toJSONString(kaipingJson));
//            }

            log.info("碳碳星球-推送逻辑结束");
//            redisUtils.set(key, offset);
        } catch (Exception e) {
            log.error("碳碳星球-【消息推送】kafka消费逻辑异常{}", e);
            ackFlag = false;
        } finally {
//            if (ackFlag) {
//                ack.acknowledge();
//            }
        }
    }

//    /**
//     * 计算减碳量
//     *
//     * @param abstractSceneReqDto 数据
//     * @return  公交减碳量
//     */
//
//    public  calculate( ) {
//        // 乘坐1次公交获得150g减排量，乘坐两次获得300g减排量单日该行为获得减排量上限为300g。减排量于次日凌晨1点发放。
//        String businessDate = getBusinessDate(abstractSceneReqDto);
//        DateTime dateTime = DateUtil.parse(businessDate, DatePattern.NORM_DATETIME_PATTERN);
//
//        DateTime beginOfDay = DateUtil.beginOfDay(dateTime);
//        DateTime endedOfDay = DateUtil.endOfDay(dateTime);
//
//        // 查询当日发放次数
//        Integer total = sceneBusDataService.lambdaQuery()
//                .eq(SceneBusData::getClientId, abstractSceneReqDto.getClientId())
//                .eq(SceneBusData::getPhone, getEncryptPhone(abstractSceneReqDto.getPhone()))
//                .eq(SceneBusData::getStatus, 1)
//                .eq(SceneBusData::getException, 0)
//                .ge(SceneBusData::getPayTime, beginOfDay)
//                .lt(SceneBusData::getPayTime, endedOfDay)
//                .count();
//
//        CalculateCarbonDto calculateCarbonDto = new CalculateCarbonDto();
//        calculateCarbonDto.setCarbonTotal(new BigDecimal(150));
//        if (total >= 2 ){
//            calculateCarbonDto.setStatus(3);
//            calculateCarbonDto.setActualCarbonTotal(BigDecimal.ZERO);
//            return calculateCarbonDto;
//        }
//        calculateCarbonDto.setStatus(1);
//        calculateCarbonDto.setActualCarbonTotal(new BigDecimal(150));
//        return calculateCarbonDto;
//    }

    /**
     * 获取用户所有的未领取的信息
     * 根据手机号 和 未领取 进行识别
     *
     * @param sceneRideCodeData
     * @return List<SceneRideCodeData>
     */
    @Override
    public List<SceneRideCodeData> queryList(SceneRideCodeData sceneRideCodeData) {
        sceneRideCodeData.setStatus(0);
        return baseMapper.selectList(buildQueryWrapper(sceneRideCodeData));
    }

    /**
     * 根据传递过来的手机号 进行数据领取
     * 1.根据手机号领取前 写入日志 获取本次领取的积分id信息 写入日志表
     * 1.直接更新表中信息为 1
     *
     * @param sceneRideCodeData
     * @return
     */
    @Override
    public Long updateClaimPointsByPhone(SceneRideCodeData sceneRideCodeData) throws Exception {
        Long reqData = 0L;
        List<SceneRideCodeData> list = baseMapper.selectListByPhone(sceneRideCodeData);
        if (list != null && list.size() > 0) {
            for (SceneRideCodeData item : list) {
                TblMemberEntity tblMemberEntity = baseMapper.selectUserByPhone(item.getPhone());
                if (tblMemberEntity != null) {
                    //上传
                    MemberBehaviorRecordRequestDTO memberBehaviorRecordRequestDTO = new MemberBehaviorRecordRequestDTO();
                    memberBehaviorRecordRequestDTO.setBehaviorId(item.getId());
                    memberBehaviorRecordRequestDTO.setMemberId(tblMemberEntity.getId());
                    memberBehaviorRecordRequestDTO.setSceneId(item.getSceneId());
                    memberBehaviorRecordRequestDTO.setBehaviorTime(DateUtil.now());
                    memberBehaviorRecordRequestDTO.setReceiveTime(DateUtil.now());
                    memberBehaviorRecordRequestDTO.setCarbonNumOrigin(item.getCarbonNumTotal());
                    memberBehaviorRecordRequestDTO.setCarbonNumBalance(item.getCarbonNumAdd());
                    memberBehaviorRecordRequestDTO.setPointsNumBalance(null);

                    OpenApiHttpReq.OpenApiHttpReqBuilder builder = OpenApiHttpReq.builder()
                            .url(saasOpenApiConfig.getUrl() + "/scene/memberBehaviorRecord/save")
                            .httpMethod(HttpMethod.POST)
                            .header(ImmutableMap.of("TEST-HEADER", "testValue"))
                            .body(JSON.toJSONString(memberBehaviorRecordRequestDTO))
                            .timestamp(new Date());
                    ResponseEntity<String> res = SaasOpenApiHttpTool.callHttp(builder.build(), saasOpenApiConfig, restTemplateConfig.restTemplate());


                    String orderCode = IdUtil.simpleUUID();
                    //出账
                    MemberAccReduceCarbonInOrOutResponseDTO memberAccReduceCarbonInOrOutResponseDTO = new MemberAccReduceCarbonInOrOutResponseDTO();

                    memberAccReduceCarbonInOrOutResponseDTO.setTenantCode(1777962408355201024L);
                    memberAccReduceCarbonInOrOutResponseDTO.setCarbonNum(1);
                    memberAccReduceCarbonInOrOutResponseDTO.setType(1);
                    memberAccReduceCarbonInOrOutResponseDTO.setMemberId(tblMemberEntity.getId());
                    memberAccReduceCarbonInOrOutResponseDTO.setOrderCode(orderCode);
                    memberAccReduceCarbonInOrOutResponseDTO.setSceneCode(item.getSceneId());
                    memberAccReduceCarbonInOrOutResponseDTO.setSceneName(item.getSceneName());


                    OpenApiHttpReq.OpenApiHttpReqBuilder builder1 = OpenApiHttpReq.builder()
                            .url(saasOpenApiConfig.getUrl() + "/account/memberCarbonDetail/save")
                            .httpMethod(HttpMethod.POST)
                            .header(ImmutableMap.of("TEST-HEADER", "testValue"))
                            .body(JSON.toJSONString(memberAccReduceCarbonInOrOutResponseDTO))
                            .timestamp(new Date());
                    ResponseEntity<String> res2 = SaasOpenApiHttpTool.callHttp(builder1.build(), saasOpenApiConfig, restTemplateConfig.restTemplate());

                    //系统更新

                    item.setStatus(1);
                    baseMapper.updateById(item);
                    //写入日志
                    TblRideCodeLog tblRideCodeLog = new TblRideCodeLog();
                    tblRideCodeLog.setOrderCode(orderCode);
                    tblRideCodeLog.setRideCodeId(String.valueOf(item.getId()));
                    tblRideCodeLog.setRequestBody(item.toString() + "|" + memberBehaviorRecordRequestDTO.toString() + "|" + memberAccReduceCarbonInOrOutResponseDTO.toString());
                    tblRideCodeLog.setMsg(res.toString() + "|" + res2.toString());
                    tblRideCodeLogMapper.insert(tblRideCodeLog);
                }
            }
        }


        return reqData;
    }

    public Wrapper<SceneRideCodeData> buildQueryWrapper(SceneRideCodeData sceneRideCodeData) {
        QueryWrapper<SceneRideCodeData> wrapper = Wrappers.query();
        wrapper.eq(com.chengyu.core.utils.StringUtils.isNotBlank(sceneRideCodeData.getPhone()), "phone", sceneRideCodeData.getPhone())
                .eq(sceneRideCodeData.getStatus() >= 0, "status", sceneRideCodeData.getStatus());
        return wrapper;
    }


}
